package com.dao.impl;

import com.dao.BaseDao;
import com.dao.intf.BlogDao;
import com.entity.Blog;

import java.util.List;

public class BlogDaoImpl extends BaseDao implements BlogDao {

    @Override
    public Integer queryUserIdByUserName(String userName) {
        String sql="SELECT `id` FROM `user` WHERE `username`=?";

        return (Integer) queryForSingleValue(sql,userName);
    }

    @Override
    public String  queryUserNameByUserId(Integer userId) {
        String sql="SELECT `username` FROM `user` WHERE `id` =?";

        return (String) queryForSingleValue(sql,userId);
    }


    @Override
    public List<Blog> queryBlogByUserName(String userName) {


//        String sql="SELECT `id` FROM `user` WHERE `username`=?";
//
//        Integer id = (Integer) queryForSingleValue(sql, userName);
        Integer id = queryUserIdByUserName(userName);
        String sql1="SELECT `id` , `content`,`favour` FROM `blog` WHERE `userId`=?";
        return queryForList(Blog.class,sql1,id);
    }

    @Override
    public Blog querySingleBlogByBlogId(Integer blogId) {
//        Integer id = queryUserIdByUserName(blogId);
        String sql="SELECT `id`,`userId` ,`content`,`favour` FROM `blog` WHERE `id`=?";
        return queryForOne(Blog.class,sql,blogId);
    }

    @Override
    public int  deleteBlogByBlogId(Integer blogId) {

        String sql=" DELETE FROM `blog` WHERE id = ?";

        update(sql,blogId);
        String sql1="DELETE FROM `collection` WHERE `blogId` = ?";

        update(sql1,blogId);
        String sql2="DELETE FROM `comment` WHERE `blogId` = ?";

        update(sql2,blogId);
        String sql3="DELETE FROM `favour` WHERE `blogId` = ?";

        return update(sql3,blogId);

    }

    @Override
    public int updateBlog(String content,Integer blogId) {

        String sql=" UPDATE `blog` SET `content`=? WHERE `id`=?";
        return update(sql,content,blogId);
    }

    @Override
    public int addBlog(String content, Integer userId) {

        String sql=" INSERT INTO `blog`(`userId`,`content`,`favour`) VALUES(?,?,0)";
        return  update(sql,userId,content);
    }

    @Override
    public Integer queryForPageTotalCount(Integer userId) {
        String sql = " SELECT COUNT(*) FROM `blog` WHERE  `userId`=?";

        Number count = (Number) queryForSingleValue(sql,userId);
        return count.intValue();
    }

    @Override
    public List<Blog> queryForPageItems(int begin, int pageSize,Integer userId) {
        String sql = "SELECT * FROM `blog` WHERE  `userId`=? LIMIT ?,?";
        return queryForList(Blog.class,sql,userId,begin,pageSize);
    }

}
